package jp.co.recruit_lifestyle.ohos.widget;

import ohos.agp.animation.AnimatorValue;

/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class ValueAnimator extends AnimatorValue {

    private float mValue;
    private float mStart;
    private float mEnd;
    private float mFactor;

    private AnimatorUpdateListener mUpdateListener;

    public ValueAnimator() {
    }

    public ValueAnimator(float start, float end) {
        mStart = start;
        mEnd = end;
        mFactor = mEnd - mStart;
        mValue = mStart;
    }

    public static ValueAnimator ofFloat(float start, float end) {
        ValueAnimator anim = new ValueAnimator();
        anim.setFloatValues(start, end);
        return anim;
    }

    public void setFloatValues(float start, float end) {
        mStart = start;
        mEnd = end;
        mFactor = mEnd - mStart;
        mValue = start;
    }

    public void addUpdateListener(AnimatorUpdateListener listener) {
        mUpdateListener = listener;
        super.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                mValue = mFactor * v + mStart;
                if (mUpdateListener != null) {
                    listener.onUpdate(animatorValue, mValue);
                }
            }
        });
    }

    public float getAnimatedValue() {
        return mValue;
    }

    public void removeUpdateListeners() {
        if (mUpdateListener == null) {
            return;
        }
        mUpdateListener = null;
    }

    public void removeAllUpdateListeners() {
        removeUpdateListeners();
    }

    public interface AnimatorUpdateListener {
        void onUpdate(AnimatorValue animatorValue, float value);
    }
}
